package ntu.metaweb.http;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

@SuppressWarnings("restriction" )
public class MetawebHTTPHandler implements HttpHandler{
	private HashMap<String,CommandHandler> commandHandler;
	
	public MetawebHTTPHandler() {
		this.commandHandler = new HashMap<String, CommandHandler>();
		this.commandHandler.put("get_comments", new GetCommentsHandler());
		this.commandHandler.put("get_page_rating", new GetPageRatingHandler());
		this.commandHandler.put("get_page_rating_bulk", new GetPageRatingBulkHandler());
		this.commandHandler.put("update_page_rating", new UpdatePageRatingHandler());
		this.commandHandler.put("user_login", new LoginHandler());
		this.commandHandler.put("new_comment", new NewCommentHandler());
		this.commandHandler.put("get_page_tags", new GetPageTagsHandler());
		this.commandHandler.put("add_tag", new AddTagHandler());
		this.commandHandler.put("get_pages_with_tag", new GetPagesWithTagHandler());
		this.commandHandler.put("get_title", new GetTitleHandler());
		this.commandHandler.put("update_title", new UpdatePageTitleHandler());
		this.commandHandler.put("rate_tag", new UpdateTagRatingHandler());
		this.commandHandler.put("rate_comment", new UpdateCommentRatingHandler());
		this.commandHandler.put("add_link", new AddLinkHandler());
		this.commandHandler.put("get_links", new GetLinkHandler());
		this.commandHandler.put("get_link_comment", new GetLinkCommentHandler());
		this.commandHandler.put("rate_link", new UpdateLinkRatingHandler());
		this.commandHandler.put("delete_tag", new DeleteTagHandler());
		this.commandHandler.put("delete_link", new DeleteLinkHandler());
		this.commandHandler.put("register_new_user", new RegisterNewUserHandler());
		this.commandHandler.put("follow_contact", new FollowContactHandler());
		this.commandHandler.put("get_contact_list", new GetContactListHandler());
	}
	
	public void handle(HttpExchange exchange) throws IOException {
		
    InputStream body = exchange.getRequestBody();
    byte b[] = new byte[20];
    int readLength = 0;
    String bodyString = "";
    do {
    	readLength = body.read(b, 0, 20);
    	if (readLength > 0) {
    		bodyString += new String(b, 0, readLength);
    	}
    } while (readLength != -1);
    String temp[] = bodyString.split("&");
    HashMap<String,String> param = new HashMap<String,String>();
    for (int i = 0; i < temp.length; ++i) {
    	String temp2[] = temp[i].split("=");
    	param.put(temp2[0], temp2[1]);
    }
    
		System.out.println(bodyString);
		if (param.containsKey("command") &&
				this.commandHandler.get(param.get("command")) != null) {
			this.commandHandler.get(param.get("command")).handleCommand(exchange, param);
		} else {
			/** command not available **/
			exchange.close();
		}
	}
}
